#include "ring_buffer.h"
#include "FreeRTOS.h"
#include "cmsis_os2.h"
#include "task.h"
#include "semphr.h"
#include <stdbool.h>


bool ringBuf_is_empty(ringBuffer_t* ring_buff)
{
    if(ring_buff->head == ring_buff->tail)
    {
        return true;
    }

    return false;
}

bool ringBuf_is_full(ringBuffer_t* ring_buff)
{
    if(((ring_buff->tail + 1) % MAX_BUFF_SIZE) == ring_buff->head)
    {
        return true;
    }

    return false;
}

uint8_t ringBuf_Write(ringBuffer_t* ring_buff, uint8_t data)
{
    if(ringBuf_is_full(ring_buff)) {
        return 0;
    }

    ring_buff->ringBuf[ring_buff->tail] = data; 

    ring_buff->tail++;
    if (ring_buff->tail >= MAX_BUFF_SIZE) /* when the tail reaches to the MAX SIZE of the buffer, offset the tail to the start of the buffer, which implements as a circular queue. */
        ring_buff->tail = 0;

    return 1;
}



void ringBuf_clear(ringBuffer_t* ring_buff)
{
	ring_buff->head = 0;
	ring_buff->tail = 0;
}


uint8_t ringBuf_Read(ringBuffer_t* ring_buff, uint8_t* pData)
{
    uint32_t head = ring_buff->head;
	if (ringBuf_is_empty(ring_buff)) {   	/* when the head already reached to the tail, it means there is no data. */
		return 0;
	} 	
    
	*pData = ring_buff->ringBuf[head];    /* if the buffer is not null, read the data which is indicated by head and then offset the head. */

    ring_buff->head++;
    if (ring_buff->head >= MAX_BUFF_SIZE)
        ring_buff->head = 0;


    return 1;     /* return 1 --> data in the ring_buff is read successfully. */ 
}

